package com.example.wacoffee_user.controller;


import cn.hutool.core.bean.BeanUtil;
import com.example.wacoffee_user.pojo.entity.User;
import com.example.wacoffee_user.pojo.vo.registerVo;
import com.example.wacoffee_user.service.IMeService;
import com.example.wacoffee_user.utils.CurrentHoler;
import com.example.wacoffee_user.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/register")
public class registerController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IMeService userService;

    @PostMapping
    public Result register(@RequestBody registerVo registerVo){
        System.out.println(registerVo);
        String targetEmail=registerVo.getEmail();
        // 校验邮箱格式
        if (targetEmail == null || !targetEmail.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            return Result.error("邮箱格式不正确");
        }
        // 校验是否是 QQ 邮箱
        if (!targetEmail.endsWith("@qq.com")) {
            return Result.error("仅支持 QQ 邮箱");
        }
        // 校验用户名
        if (registerVo.getUsername() == null || registerVo.getUsername().length() < 2 || registerVo.getUsername().length() > 16) {
            return Result.error("用户名长度在 2 到 16 个字符");
        }
        if (registerVo.getPassword() == null || registerVo.getPassword().length() < 6 || registerVo.getPassword().length() > 16) {
            return Result.error("密码长度在 6 到 20 个字符");
        }
        if (!registerVo.getPassword().equals(registerVo.getConfirmPassword())) {
            return Result.error("两次输入的密码不一致");
        }
        if (registerVo.getPhone() == null || !registerVo.getPhone().matches("^1[3-9]\\d{9}$")) {
            return Result.error("手机号格式不正确");
        }
        if(registerVo.getCode()==null||registerVo.getCode().length()!=6|| !registerVo.getCode().
                equals(stringRedisTemplate.opsForValue().get("authCode:"+ registerVo.getEmail()))){
            return Result.error("验证码错误");
        }
        User user = BeanUtil.copyProperties(registerVo, User.class);
        user.setCreateTime(LocalDateTime.now());
        userService.save(user);
        return Result.success();
    }
}
